//
//  CTCRapidConsultResultVC.m
//  CTC
//
//  Created by 李小龙 on 2017/3/21.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCRapidConsultResultVC.h"
#import "CTCRapidAnswerCell.h"
#import "CTCRapidQuestionCell.h"
#import "CTCAnswerResponderVC.h"

@interface CTCRapidConsultResultVC ()<UIPopoverPresentationControllerDelegate>

/** 回答模型数组 */
@property (nonatomic, strong) NSMutableArray *answersArr;

/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger questionStatus;

@end

@implementation CTCRapidConsultResultVC
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"咨询详情";
    
    [self setupTableView];
    
    [self getAnswerData];
    
    if (self.isPush) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kReloadRepaidHistoryListNotification object:nil];
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.answersArr.count) {
        return 2;
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!section) {
        return 1;
    }
    
    return self.answersArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section) {
        CTCRapidAnswerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCRapidAnswerCell" forIndexPath:indexPath];
        CTCAnswerModel *model = [self.answersArr firstObject];
        cell.answerModel = model;

        if ((self.answerStatus == 1)||(self.answerStatus == 4)) {
            cell.replyBtn.hidden = YES;
        }
        else {
            if (model.stage ==2 ) {
                cell.replyBtn.hidden = NO;
            } else {
                cell.replyBtn.hidden = YES;
            }
        }
        __weak typeof(self) weakself = self;
        
        cell.replyBtnClickBlock = ^(){
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"CTCResponderVC" bundle:nil];
            CTCAnswerResponderVC *vc = [story instantiateViewControllerWithIdentifier:@"CTCAnswerResponderVC"];
            vc.uuid = model.uuid;
            vc.answerSuccessBlock = ^(){
                [weakself getAnswerData];
            };
            
            [weakself.navigationController pushViewController:vc animated:YES];
        };

        return cell;
    }
    
    CTCRapidQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCRapidQuestionCell" forIndexPath:indexPath];
    cell.questionModel = self.questionModel;
    
    if (self.questionStatus == 1) {
        cell.statusLabel.backgroundColor = HEXCOLOR(0x2daee5);
        cell.statusLabel.text = @"被采纳";
    }else if (self.questionStatus == 4) {
        cell.statusLabel.backgroundColor = HEXCOLOR(0xff0000);
        cell.statusLabel.text = @"已过期";
    }
    else {
        cell.statusLabel.backgroundColor = HEXCOLOR(0xf79e06);
        cell.statusLabel.text = @"未被采纳";
    }
    return cell;
}

- (void)setupTableView
{
    self.tableView.backgroundColor = HEXCOLOR(0xEEEDEE);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCRapidQuestionCell class]) bundle:nil] forCellReuseIdentifier:@"CTCRapidQuestionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCRapidAnswerCell class]) bundle:nil] forCellReuseIdentifier:@"CTCRapidAnswerCell"];

    
    self.tableView.estimatedRowHeight = 500;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getAnswerData)];
//    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getAnswerData)];
}



- (void)getAnswerData
{
    
    NSString *url = kRapidDetailUrl;
    NSMutableDictionary *parmaDic = [NSMutableDictionary dictionary];
    parmaDic[@"uuid"] = self.questionModel.uuid;
    
    [MBProgressHUD showAnimationHUD];;
    [RequestTool POST:url
           parameters:parmaDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"responseObject---------:%@", responseObject);
                  [MBProgressHUD hideHUD];
                  [self stopRefresh];
                  
                  CTCAnswerListModel *model = [CTCAnswerListModel yy_modelWithJSON:responseObject];
                  NSInteger code = [model.code integerValue];
                  if (code == 1) {
//                      [MBProgressHUD showSuccessMessage:model.des];
                      [MBProgressHUD hideHUD];
                      if (self.answersArr && self.answersArr.count) {
                          [self.answersArr removeAllObjects];
                      }
                      
                      self.questionStatus = [model.answerModel.status integerValue];
                      
                      [self.answersArr addObject:model.answerModel];
                      
                      [self.tableView reloadData];
                  } else {
                      [MBProgressHUD showErrorMessage:model.des];
                      
                      if (code == 2) {
                          CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccess = ^(){
                              [weakself getAnswerData];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"error---------:%@",error);
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }];
}


- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

-(NSMutableArray *)answersArr
{
    if (!_answersArr) {
        _answersArr = [NSMutableArray array];
    }
    
    return _answersArr;
}


@end
